#include <QHeaderView>
#include <QFileInfo>
#include <QDir>
#include "filelistview.h"
#include "filelistmodel.h"
#include "common.h"

FileListView::FileListView(QWidget *parent) :
    QTableView(parent)
{
    m_model = new FileListModel(this);
    setModel(m_model);
    setMinimumSize(490,280);
    setSelectionBehavior(QAbstractItemView::SelectRows);
    setAlternatingRowColors(true);
    verticalHeader()->hide();
    horizontalHeader()->setClickable(false);
    horizontalHeader()->setStretchLastSection(true);
    horizontalHeader()->resizeSection(horizontalHeader()->visualIndex(Convert::FileInfo_duration), 70);
    horizontalHeader()->resizeSection(horizontalHeader()->visualIndex(Convert::FileInfo_outFormat), 70);
    setVerticalScrollMode(QAbstractItemView::ScrollPerPixel);
    setHorizontalScrollMode(QAbstractItemView::ScrollPerPixel);
    setShowGrid(false);
    setWordWrap(false);
    setStyleSheet("QTableView{color: #FFFFFF;alternate-background-color: #2E4653;"
                  "background-color: #2A2A2A;"
                  "selection-background-color: #121212}");
    horizontalHeader()->setStyleSheet("QHeaderView::section{border-image: url(" + IMG_DIR + "tableheader_section.png) 2 5 5 5;"
                                      "border-width: 2 5 5 5;"
                                      "color: white;padding-left: 4px;font-weight: 700;}"
                                      "QHeaderView::section:last{border-image: url(" + IMG_DIR + "tableheader_section_last.png) 2 5 5 5;"
                                      "border-width: 2 5 5 5;}");
    connect(selectionModel(), SIGNAL(selectionChanged(const QItemSelection&, const QItemSelection&)), this, SLOT(onSelectionChanged(const QItemSelection&, const QItemSelection&)));
}

void FileListView::onSelectionChanged(const QItemSelection & newSelection, const QItemSelection &)
{
    bool hasFile = model()->rowCount();
    bool hasSelection = selectionModel()->hasSelection();
    emit signalFileSelectionChanged(hasFile, hasSelection);
}

void FileListView::addFileList(const QStringList &filelist)
{
    for (int i=0;i<filelist.count();++i){
        Convert::FileInfo item;
        item.fileName = QFileInfo(filelist.at(i)).fileName();
        item.duration = "00:13:65";
        item.outFormat = "mpg";
        item.outSize = "13M";
        item.outName = item.fileName;
        m_model->addFile(item);
    }
}

void FileListView::addDirectory(const QString &path)
{
    QDir dir(path);
    QStringList filter;
    filter << "*";
    QStringList filelist = dir.entryList(filter, QDir::Files|QDir::NoDotAndDotDot);
    addFileList(filelist);
}

void FileListView::deleteSelectedFiles()
{
    QModelIndexList indexlist = selectionModel()->selectedRows();
    m_model->removeRowsByModelIndexList(indexlist);
}
